package com.android.advertising;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.Log;

public class SendRegIdAsync extends AsyncTask<String, Void, Void> {
	Context mContext;
	SharedPreferences mPref;

	public SendRegIdAsync(Context ctx) {
		mContext = ctx;
	}

	private static final String TAG = "SendRegIdAsync";

	protected String getASCIIContentFromEntity(HttpEntity entity)
			throws IllegalStateException, IOException {
		InputStream in = entity.getContent();
		StringBuffer out = new StringBuffer();
		int n = 1;
		while (n > 0) {
			byte[] b = new byte[4096];
			n = in.read(b);
			if (n > 0)
				out.append(new String(b, 0, n));
		}
		return out.toString();
	}

	@Override
	protected Void doInBackground(String... params) {
		String regID = params[0];
		mPref = PreferenceManager.getDefaultSharedPreferences(mContext);
		String imei = mPref.getString(Constants.IMEI, null);
		if (imei == null) {
			TelephonyManager telephonyManager = (TelephonyManager) mContext
					.getSystemService(Context.TELEPHONY_SERVICE);
			imei = telephonyManager.getDeviceId();
			Editor editor = mPref.edit();
			editor.putString(Constants.IMEI, imei);
			editor.commit();
		}
		Log.i(TAG, "imei = " + imei);
		HttpClient httpClient = new DefaultHttpClient();
		HttpContext localContext = new BasicHttpContext();
		HttpPost httpPost = new HttpPost(Constants.REST_SERVER
				+ Constants.REST_REGISTER);
		HttpParams p = httpPost.getParams();
		p.setParameter("regID", "" + regID);
		p.setParameter("imei", "" + imei);
		String text = null;
		try {
			HttpResponse response = httpClient.execute(httpPost, localContext);
			HttpEntity entity = response.getEntity();
			text = getASCIIContentFromEntity(entity);
			if (text != null) {
				// parsingJSONRespone(text);
				Log.i(TAG, "" + text);
			}
		} catch (Exception e) {

		}
		return null;
	}

}
